'use client'
import React, { useEffect, useState, useRef } from 'react';
import './index.scss';
import { Spin, FloatButton, message, Image } from 'antd';
import { ChatMessage } from '../type';
import { LikeOutlined, DislikeOutlined, CopyOutlined } from '@ant-design/icons';
import { copyToClipboard } from '@/app/hook/copyToClipboard';
import Markdown from '@/app/components/MarkDown/page' 
import { readtextimg } from './fn' 
import dynamic from 'next/dynamic'
const Map = dynamic(
    () => import('@/app/components/Map/page'),
    { ssr: false }
)

// 定义一个函数，用于清理代码
function cleanCode(code: string | null) {
    const regex = /^(?:\w+\d+)?\d*\s*/gm;
    return code?.replace(regex, '');
}

interface ChatcontentProps {
    chatlist: ChatMessage[];
    setData?: (value: any) => void
}

const Chatcontent: React.FC<ChatcontentProps> = ({ chatlist, setData }) => {
    const [chatList, setchatList] = useState<any>([])

    useEffect(() => {
        setchatList(chatlist)
    }, [chatlist]);



    // 处理流式文本，跳过JSON部分
    const processStreamText = (text: string) => {
        let result = '';
        let currentPos = 0;

        while (true) {
            const jsonStart = text.indexOf('```json', currentPos);
            if (jsonStart === -1) {
                result += text.slice(currentPos);
                break;
            }

            // 添加前面的文本
            result += text.slice(currentPos, jsonStart);

            // 处理 JSON 部分
            const jsonEnd = text.indexOf('```', jsonStart + 7);
            if (jsonEnd === -1) break;

            // 解析 JSON 并添加图片
            try {
                const jsonStr = text.slice(jsonStart + 7, jsonEnd).trim();
                const jsonData = JSON.parse(jsonStr);

                // 为每个路线中的地点添加图片
                jsonData.forEach((route: any) => {
                    if (route.name) {
                        result += `![${route.name}](${readtextimg(route.name)})`;
                    }
                });
            } catch (error) {
                console.error('JSON 解析错误:', error);
            }

            currentPos = jsonEnd + 3;
        }

        return result;
    };


    // 提取JSON数据
    const extractJsonData = (text: string) => {
        const jsonMatches = text.match(/```json([\s\S]*?)```/g);
        if (!jsonMatches) return null;

        try {
            const jsonDataArray = jsonMatches.map(match => {
                const jsonStr = match.replace(/```json|```/g, '');
                return JSON.parse(jsonStr);
            });

            return jsonDataArray;
        } catch (error) {
            console.error('JSON解析错误:', error);
            return null;
        }
    };

    const readtext = (text: string) => {
        const textPart = processStreamText(text);
        const jsonDataArray = extractJsonData(text);
        return {
            textPart,
            jsonDataArray
        };
    };



    return (
        <div className='chatcontent'>
            {
                chatList.map((item: any, index: number) => {
                    const { textPart, jsonDataArray } = readtext(item.answer);
                    return <div key={item.id} className='allagent'>
                        <div className='agentContentItem agentright'>
                            <div className='agentContentTxt' style={{ backgroundColor: '#eff6ff' }}>
                                {item.query}
                            </div>
                        </div>

                        <div className='agent_img'>
                            <Image.PreviewGroup >
                                {
                                    item['file_img_list'] && item['file_img_list'].map((item: any, index: number) => {
                                        return <div key={index}>
                                            {
                                                item.thumbUrl ? <Image width={150} src={item.thumbUrl} /> : <div className='word'>
                                                    <img src="/file.svg" alt="" />
                                                    <div className='wordname'>
                                                        {item.name}
                                                    </div>
                                                </div>
                                            }
                                        </div>
                                    })
                                }
                            </Image.PreviewGroup>
                        </div>

                        <div className='agentContentItem agentleft'>
                            <img src='/logo.svg' alt="" />
                            <div className='agentContentTxt'>
                                {
                                    item.answer == '' ? <Spin /> : <>
                                        <Markdown content={textPart} />
                                    </>
                                }
                                {
                                    item['prompt'] != undefined && <div className='prompt'>
                                        {
                                            item['prompt'].map((item: any, index: number) => {
                                                return <div className='promptitem' key={index} onClick={(e) => {
                                                    e?.stopPropagation()
                                                    setData?.(item.name)
                                                }}>
                                                    {item.name}
                                                </div>
                                            })
                                        }
                                    </div>
                                }
                                {
                                    index == chatlist.length - 1 &&
                                    item.status == 'normal' && jsonDataArray &&
                                    <Map
                                        list={jsonDataArray}
                                    />
                                }
                                {
                                    item.answer != '' && item.status == 'normal' && <div className='message_icon'>
                                        <LikeOutlined className="icon like" style={{ color: item.feedback == null ? '' : (item.feedback['rating'] == 'like' ? 'green' : '') }} />
                                        <DislikeOutlined className="icon dislike" style={{ color: item.feedback == null ? '' : (item.feedback['rating'] == 'dislike' ? 'red' : '') }} />
                                        <CopyOutlined onClick={() => {
                                            message.success('复制成功')
                                            copyToClipboard(cleanCode(textPart) || '')
                                        }} />
                                    </div>
                                }

                            </div>
                        </div>
                    </div>
                })}
            <FloatButton.BackTop />
        </div >
    );
}

export default Chatcontent